﻿using KalevaAalto.DataPart.Excel.Base;
using KalevaAalto.DataPart.Excel.Models;
using OfficeOpenXml;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KalevaAalto.DataPart.Models;
using System.Reflection.Metadata.Ecma335;
using KalevaAalto.DataPart.Enums;
using System.Collections.Immutable;

namespace KalevaAalto.DataPart.Excel.Epplus
{
    internal class EpplusRange : BaseRange
    {
        private RangePos _rangePos;
        private ExcelWorksheet _worksheet;
        private ExcelRange _rng => _worksheet.Cells[_rangePos.StartPos.Row, _rangePos.StartPos.Column, _rangePos.EndPos.Row,_rangePos.EndPos.Column];
        public EpplusRange(BaseWorksheet worksheet, ExcelRange rng) :base(worksheet)
        {
            _worksheet = rng.Worksheet;
            _rangePos = new RangePos(rng.Start.Row, rng.Start.Column, rng.End.Row, rng.End.Column);
        }


        public override BaseRange this[CellPos cellPos]
            =>new EpplusRange(Worksheet, _worksheet.Cells[_rangePos.StartPos.Row + cellPos.Row - 1, _rangePos.StartPos.Column + cellPos.Column - 1]);



        public override BaseRange this[RangePos rangePos] 
            => new EpplusRange(Worksheet, _worksheet.Cells[_rangePos.StartPos.Row + rangePos.StartPos.Row - 1, _rangePos.StartPos.Row +rangePos.StartPos.Column - 1,
                _rangePos.StartPos.Column + rangePos.EndPos.Row - 1, _rangePos.StartPos.Column + rangePos.EndPos.Column - 1]);

        public override bool Merge { get => _rng.Merge; set => _rng.Merge=value; }
        public override IStyle Style => new EpplusStyle(_rng.Style);

        public override BaseRows Rows=> new EpplusRows(Worksheet, _rng.EntireRow);

        public override BaseColumns Columns =>new EpplusColumns(Worksheet, _rng.EntireColumn);

        public override RangePos Pos => _rangePos;

        public override object? Value { get =>_rng.Value; set => _rng.Value=value; }







        private static readonly IDictionary<eErrorType, ErrorType> s_errorTypes = new Dictionary<eErrorType, ErrorType>
        {
            {eErrorType.NA, ErrorType.NA},

        }.ToImmutableDictionary();

        public override ErrorType ErrorType
        {
            get
            {
                object? value = Value;
                if(value is ExcelErrorValue errorValue)
                {
                    return s_errorTypes[errorValue.Type];
                }
                else
                {
                    return ErrorType.None;
                }
            }
        }

        public override void SetTable(string tableName)
        {
            if (string.IsNullOrEmpty(tableName))
            {
                tableName = Worksheet.Name;
            }

            

            _rng.Worksheet.Tables.Add(_rng, tableName);
            
        }



        


    }
}
